<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const loading = ref(false)
const errorMessage = ref(null)
const imagePreview = ref(null)

const formData = reactive({
  name: '',
  price: '',
  category: '',
  description: '',
  image: null,
  stock: '',
  status: 'active'
})

const categories = [
  { value: '食品', label: '食品' },
  { value: '服饰', label: '服饰' },
  { value: '电子产品', label: '电子产品' },
  { value: '家居', label: '家居' },
  { value: '化妆品', label: '化妆品' },
  { value: '厨卫电器', label: '厨卫电器' },
  { value: '个护健康', label: '个护健康' },
  { value: '运动户外', label: '运动户外' },
  { value: '汽车生活', label: '汽车生活' },
  { value: '儿童玩具', label: '儿童玩具' },
  { value: '男鞋', label: '男鞋' },
  { value: '女鞋', label: '女鞋' },
  { value: '其他', label: '其他' }
]

// 处理图片上传
const handleImageChange = (event) => {
  const files = Array.from(event.target.files);
  
  // 验证文件
  for (const file of files) {
    if (file.size > 5 * 1024 * 1024) {
      errorMessage.value = '单个图片大小不能超过5MB';
      return;
    }
  }
  
  formData.image = files;
  
  // 创建预览
  imagePreview.value = [];
  files.forEach(file => {
    const reader = new FileReader();
    reader.onload = (e) => {
      imagePreview.value.push(e.target.result);
    };
    reader.readAsDataURL(file);
  });
};

const handleSubmit = async () => {
  try {
    // 表单验证
    if (!formData.name) {
      errorMessage.value = '请输入商品名称';
      return;
    }
    if (!formData.price) {
      errorMessage.value = '请输入商品价格';
      return;
    }
    if (!formData.category) {
      errorMessage.value = '请选择商品分类';
      return;
    }

    loading.value = true;
    errorMessage.value = '';

    // 创建 FormData 对象
    const submitData = new FormData();
    
    // 添加基本信息
    submitData.append('name', formData.name);
    submitData.append('price', formData.price);
    submitData.append('category', formData.category);
    submitData.append('description', formData.description || '');
    submitData.append('stock', formData.stock || 0);
    submitData.append('status', formData.status);

    // 添加图片
    if (formData.image) {
      if (Array.isArray(formData.image)) {
        formData.image.forEach(file => {
          submitData.append('image', file);
        });
      } else {
        submitData.append('image', formData.image);
      }
    }

    const response = await fetch('http://localhost:3001/api/products', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: submitData
    });

    const data = await response.json();

    if (response.ok && data.code === 200) {
      alert('添加商品成功');
      router.push('/products');
    } else {
      throw new Error(data.message || '添加失败');
    }
  } catch (error) {
    console.error('添加商品失败:', error);
    errorMessage.value = error.message || '操作失败，请稍后重试';
  } finally {
    loading.value = false;
  }
};

// 添加删除图片的方法
const removeImage = (index) => {
  // 从预览数组中移除
  imagePreview.value = imagePreview.value.filter((_, i) => i !== index);
  
  // 从表单数据中移除
  if (Array.isArray(formData.image)) {
    formData.image = Array.from(formData.image).filter((_, i) => i !== index);
  } else {
    formData.image = null;
  }
};
</script>

<template>
  <div class="add-product-page">
    <div class="page-header">
      <h2>添加商品</h2>
      <div class="header-actions">
        <button class="cancel-btn" @click="router.back()">返回</button>
      </div>
    </div>

    <div class="form-container">
      <form @submit.prevent="handleSubmit" class="product-form">
        <div class="form-layout">
          <div class="form-main">
            <div class="form-group">
              <label>商品名称 <span class="required">*</span></label>
              <input
                v-model="formData.name"
                type="text"
                placeholder="请输入商品名称"
                required
              >
            </div>

            <div class="form-group">
              <label>商品价格 <span class="required">*</span></label>
              <input
                v-model="formData.price"
                type="number"
                step="0.01"
                placeholder="请输入商品价格"
                required
              >
            </div>

            <div class="form-item">
              <label>商品分类</label>
              <div class="select-wrapper">
                <select 
                  v-model="formData.category" 
                  required
                  class="custom-select"
                >
                  <option value="" disabled>请选择分类</option>
                  <option 
                    v-for="category in categories" 
                    :key="category.value"
                    :value="category.value"
                  >
                    {{ category.label }}
                  </option>
                </select>
                <i class="fa-solid fa-chevron-down select-arrow"></i>
              </div>
            </div>

            <div class="form-group">
              <label>库存数量</label>
              <input
                v-model="formData.stock"
                type="number"
                placeholder="请输入库存数量"
              >
            </div>

            <div class="form-group">
              <label>商品状态</label>
              <select v-model="formData.status">
                <option value="active">上架</option>
                <option value="inactive">下架</option>
              </select>
            </div>

            <div class="form-group">
              <label>商品描述</label>
              <textarea
                v-model="formData.description"
                rows="4"
                placeholder="请输入商品描述"
              ></textarea>
            </div>
          </div>

          <div class="form-side">
            <div class="form-group">
              <label>商品图片</label>
              <div class="image-upload">
                <div class="image-preview-list">
                  <div 
                    v-for="(preview, index) in imagePreview" 
                    :key="index"
                    class="preview-item"
                  >
                    <img :src="preview" :alt="`预览图${index + 1}`">
                    <div class="preview-delete" @click="removeImage(index)">
                      <i class="fa-solid fa-times"></i>
                    </div>
                  </div>
                  <div 
                    v-if="!imagePreview || imagePreview.length < 5"
                    class="upload-trigger"
                    @click="$refs.imageInput.click()"
                  >
                    <i class="fa-solid fa-plus"></i>
                    <span>上传图片</span>
                  </div>
                </div>
                <input
                  ref="imageInput"
                  type="file"
                  accept="image/*"
                  multiple
                  @change="handleImageChange"
                  style="display: none"
                >
                <div class="image-tip">
                  支持jpg、png格式，单张图片不超过5MB，最多上传5张
                </div>
              </div>
            </div>
          </div>
        </div>

        <div v-if="errorMessage" class="error-message">
          {{ errorMessage }}
        </div>

        <div class="form-actions">
          <button type="submit" :disabled="loading" class="submit-btn">
            {{ loading ? '添加中...' : '添加商品' }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<style scoped>
.add-product-page {
  padding: 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.form-layout {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 24px;
}

.form-main {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

label {
  font-weight: 500;
  color: #333;
}

.required {
  color: #ff4d4f;
  margin-left: 4px;
}

input, select, textarea {
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
}

input:focus, select:focus, textarea:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24,144,255,0.2);
}

textarea {
  resize: vertical;
}

.image-upload {
  width: 100%;
}

.image-preview {
  width: 100%;
  height: 200px;
  border: 2px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
}

.image-preview:hover {
  border-color: #1890ff;
}

.image-preview.has-image {
  border-style: solid;
}

.image-preview img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.upload-placeholder {
  text-align: center;
  color: #999;
}

.upload-placeholder i {
  font-size: 32px;
  margin-bottom: 8px;
}

.image-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

.error-message {
  color: #ff4d4f;
  font-size: 14px;
  padding: 8px 12px;
  background: #fff2f0;
  border: 1px solid #ffccc7;
  border-radius: 4px;
  margin: 16px 0;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

.submit-btn, .cancel-btn {
  padding: 8px 24px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.submit-btn {
  background: #1890ff;
  color: white;
  border: none;
}

.submit-btn:hover {
  background: #40a9ff;
}

.submit-btn:disabled {
  background: #d9d9d9;
  cursor: not-allowed;
}

.cancel-btn {
  background: white;
  border: 1px solid #d9d9d9;
}

.cancel-btn:hover {
  color: #1890ff;
  border-color: #1890ff;
}

@media (max-width: 768px) {
  .form-layout {
    grid-template-columns: 1fr;
  }
}

.form-item {
  margin-bottom: 20px;
}

.form-item label {
  display: block;
  margin-bottom: 8px;
  color: var(--text-color);
  font-weight: 500;
}

.select-wrapper {
  position: relative;
  width: 100%;
}

.custom-select {
  width: 100%;
  padding: 8px 12px;
  padding-right: 32px; /* 为箭头留出空间 */
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  background: var(--bg-color);
  color: var(--text-color);
  font-size: 14px;
  appearance: none; /* 移除默认的下拉箭头 */
  cursor: pointer;
  transition: all 0.3s;
}

.custom-select:focus {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(var(--primary-color-rgb), 0.1);
  outline: none;
}

.custom-select:hover {
  border-color: var(--primary-color);
}

.custom-select option {
  padding: 8px;
  background: var(--bg-color);
  color: var(--text-color);
}

.custom-select option:hover {
  background: var(--primary-color);
  color: white;
}

.select-arrow {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: var(--text-color-secondary);
  pointer-events: none; /* 确保箭头不会干扰选择 */
  transition: transform 0.3s;
}

.custom-select:focus + .select-arrow {
  transform: translateY(-50%) rotate(180deg);
  color: var(--primary-color);
}

/* 禁用状态样式 */
.custom-select:disabled {
  background: var(--bg-color-secondary);
  cursor: not-allowed;
  opacity: 0.7;
}

/* 错误状态样式 */
.custom-select.error {
  border-color: #ff4d4f;
}

/* 暗色主题适配 */
[data-theme='dark'] .custom-select {
  background: var(--bg-color);
  color: var(--text-color);
}

[data-theme='dark'] .custom-select option {
  background: var(--bg-color);
  color: var(--text-color);
}

.image-preview-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 12px;
}

.preview-item {
  position: relative;
  width: 100px;
  height: 100px;
  border-radius: 4px;
  overflow: hidden;
}

.preview-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.preview-delete {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 20px;
  height: 20px;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
}

.preview-delete:hover {
  background: rgba(0, 0, 0, 0.7);
}

.upload-trigger {
  width: 100px;
  height: 100px;
  border: 2px dashed var(--border-color);
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-trigger:hover {
  border-color: var(--primary-color);
  color: var(--primary-color);
}

.upload-trigger i {
  font-size: 24px;
  margin-bottom: 8px;
}
</style> 